{% from 'IcsocUIBundle:Macro:actions.html.twig' import button %}
<link type="text/css" rel="stylesheet" href="{{ asset('bundles/icsocui/plugin/select2/select2.css') }}"/>
<div class="widget-main">
    {% for key, monitorConfig in monitorConfigs %}
        <div class="widget-box widget-color-blue3" id="{{ key }}" config-id="{{ monitorConfig.id }}">
            <div class="widget-header widget-header-small">
                <h6 class="widget-title">
                    <input type="text" value="{{ monitorConfig.name }}" name="monitor_name" maxlength="15">
                    {{ "refresh time"|trans }}<input type="text" value="{{ monitorConfig.refresh }}" onblur="check_refresh(this)" name="refresh" style="width:35px;">
                </h6>
                <div class="widget-toolbar">
                    <a href="#" style="color: #ffffff">
                        <i class="ace-icon fa fa-minus"> {{ 'Delete'|trans }} </i>
                    </a>
                    <a href="#" style="color: #ffffff">
                        <i class="ace-icon fa fa-eye"> {{ 'preview'|trans }} </i>
                    </a>
                    <a href="#" data-action="collapse">
                        <i class="ace-icon fa fa-chevron-up"></i>
                    </a>
                </div>
            </div>

            <div class="widget-body">
                <div class="row widget-main">
                    {% for items, mainField in monitorConfig.mainFields %}
                        <div class="widget-header widget-header-small">
                            <h6 class="widget-title">{{ items|trans() }}</h6>
                            <label style="margin-left: 5px">
                                <input type="checkbox" data-text="{{ items }}" class="ace" datatype="is-show" {% if mainField.is_show is defined and mainField.is_show == true %} checked {% endif %} />
                                <span class="lbl">{{ "isshow"|trans }}</span>
                            </label>
                        </div>
                        <div class="row widget-main {% if mainField.is_show is not defined or mainField.is_show != true %} hide {% endif %}">
                            {% for item, itemValue in mainField.fields %}
                                <div class="col-lg-2 col-sm-3 col-xs-6">
                                    <label>
                                        <input class="ace item" type="checkbox" value="{{ item }}" data-type="{{ items }}" data-text="{{ itemValue.text|trans }}" {% if itemValue.checked is defined and itemValue.checked == true  %} checked {% endif %} />
                                        <span class="lbl"> {{ itemValue.text|trans }}</span>
                                    </label>
                                    {% if item == 'ivrInboundTotalNum' and items == 'queue' %}
                                        <a href="#" title="">
                                            <i class="ace-icon fa fa-edit" data-type="{{ items }}" data-text="{{ itemValue.text|trans }}" data-id="{{ item }}"></i>
                                        </a>
                                        <a href="#" title="配置中继号码">
                                            <i class="ace-icon fa fa-cogs" data-type="{{ items }}" data-text="{{ itemValue.text|trans }}" data-id="{{ item }}"></i>
                                        </a>
                                    {% else %}
                                        <a href="#" title="">
                                            <i class="ace-icon fa fa-edit" data-type="{{ items }}" data-text="{{ itemValue.text|trans }}" data-id="{{ item }}"></i>
                                        </a>
                                    {% endif %}
                                </div>
                            {% endfor %}
                        </div>
                    {% endfor %}
                    <div class="row widget-main">
                        <div class="widget-header widget-header-small">
                            <h6 class="widget-title">{{ "agent status"|trans }}</h6>
                            <label style="margin-left: 5px">
                                <input type="checkbox" name="agent-show" class="ace" datatype="is-show" data-text="agent" {% if monitorConfig.agent.is_show is defined and monitorConfig.agent.is_show == true %} checked {% endif %} />
                                <span class="lbl">{{ "isshow"|trans }}</span>
                            </label>
                            {% if isEnableGroup == true %}
                                <label style="margin-left: 12px">
                                    <input type="checkbox" name="agent-group-show" class="ace" datatype="is-bygroup-show" data-text="group-agent" {% if monitorConfig.agent.is_group_show is defined and monitorConfig.agent.is_group_show == true %} checked {% endif %} />
                                    <span class="lbl">{{ 'is group show'|trans }}</span>
                                </label>
                            {% endif %}
                        </div>
                        <div class="row widget-main {% if monitorConfig.agent.is_show is not defined or monitorConfig.agent.is_show != true %} hide {% endif %}">
                            {% if isEnableGroup == true %}
                                {#<div class="col-lg-12 col-sm-3 col-xs-6">
                                    <label> {{ "show type"|trans }}</label>
                                    <label class="radio-inline">
                                        <input type="radio" class="ace" name="show-type-{{ key }}" value="1" {% if monitorConfig.agent.type == 1 %} checked {% endif %}">
                                        <span class="lbl"> {{ "By Queue"|trans }} </span>
                                    </label>

                                    <label class="radio-inline">
                                        <input type="radio" class="ace" name="show-type-{{ key }}" value="2" {% if monitorConfig.agent.type == 2 %} checked {% endif %}">
                                        <span class="lbl"> {{ "By Group"|trans }} </span>
                                    </label>
                                </div>#}
                            {% endif %}
                            {% for key, agentState in monitorConfig.agent.fields %}
                                {% for k, state in agentState %}
                                    <div class="col-lg-2 col-sm-3 col-xs-6">
                                        <label>
                                            <span class="lbl"> {{ state }}</span>
                                        </label>
                                        <a href="#" title="">
                                            <i class="ace-icon fa fa-edit" datatype="agent" data-type="{{ key }}" data-text="{{ state }}" data-id="{{ k }}"></i>
                                        </a>
                                    </div>
                                {% else %}
                                    <div class="col-lg-2 col-sm-3 col-xs-6">
                                        <label>
                                            <span class="lbl"> {{ agentState }}</span>
                                        </label>
                                        <a href="#" title="">
                                            <i class="ace-icon fa fa-edit" datatype="agent" data-id="{{ agentState }}" data-type="{{ key }}" data-text="{{ agentState }}"></i>
                                        </a>
                                    </div>
                                {% endfor %}
                            {% endfor %}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    {% endfor %}
</div>

<!-- #section:指标计算项配置 -->
<div id="dialog-message-monitor" class="hide" style="height: auto">
    <div class="widget-main hide" id="monitor-itmes-widget" style="margin-bottom: 120px">
        <div class="row hide">
            <div class="col-xs-12">
                <form class="form-horizontal" role="form">
                    <div class="form-group">
                        <label class="col-sm-3 control-label no-padding-right" for="form-field-1"> {{ 'Background Color'|trans }} </label>
                        <div class="col-sm-9">
                            <input id="background" name="background" type="text" class="input-small colorpicker-input col-sm-9" maxlength="7" />
                            <input name="background-hide" type="hidden" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label no-padding-right" for="form-field-1"> {{ 'Font Color'|trans }} </label>
                        <div class="col-sm-9">
                            <input id="fontColor" name="fontColor" type="text" class="input-small colorpicker-input col-sm-9" maxlength="7" />
                        </div>
                    </div>
                    <div class="form-group" id="time-threshold">
                        <label class="control-label col-sm-3 no-padding-right" for="form-field-1"> {{ 'time threshold'|trans }}</label>
                        <div class="col-sm-9">
                            <input type="text" name="threshold" class="input-small col-sm-9" placeholder="{{ 'time threshold'|trans }}" />&nbsp;&nbsp;&nbsp;{{ 'secs'|trans }}
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label no-padding-right" for="form-field-1"> {{ 'Font Size'|trans }} </label>
                        <div class="col-sm-9">
                            <input type="text" class="input-mini fontSize" id="fontSize" name="fontSize" readonly maxlength="2" />
                        </div>
                    </div>
                    <div class="form-group" id="valid-secs-grou">
                        <label class="col-sm-3 control-label no-padding-right" for="form-field-1"> {{ 'Effective duration'|trans }} </label>
                        <div class="col-sm-9">
                            <input type="text" id="valid_call_secs" class="col-sm-9" placeholder="{{ 'Valid Secs, Larger Than This Value Is Valid Call'|trans }}" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label no-padding-right" for="form-field-1"> &nbsp; </label>
                        <div class="col-sm-9 monitor-itmes-show-demo"></div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <div class="widget-main" id="xsecs-widget" style="margin-bottom: 120px">
        <div class="row hide">
            <div class="control-group col-sm-2">
                <label class="control-label no-padding-right" for="form-field-1"> {{ 'duration'|trans }} </label>
                <br>
                <input type="text" name="xsecs" class="col-sm-9" placeholder="{{ 'duration'|trans }}" maxlength="3" />
            </div>
            <div class="control-group col-sm-3">
                <label class="control-label no-padding-right" for="form-field-1"> {{ 'Font Color'|trans }} </label>
                <br>
                <div class="">
                    <input name="fontColor" type="text" class="input-small colorpicker-input" maxlength="7" />
                </div>
            </div>
            <div class="control-group col-sm-3">
                <label class="control-label no-padding-right" for="form-field-1"> {{ 'Background Color'|trans }} </label>
                <br>
                <div>
                    <input name="background" type="text" class="input-small colorpicker-input col-sm-9" maxlength="7" />
                    <input name="background-hide" type="hidden" />
                </div>
            </div>
            <div class="control-group col-sm-3">
                <label class="control-label no-padding-right " for="form-field-1"> {{ 'Font Size'|trans }} </label>
                <br>
                <div>
                    <input type="text" class="input-mini fontSize" name="fontSize" readonly maxlength="2"  />
                </div>
            </div>
            <div class="control-group col-sm-1">
                <label class="control-label no-padding-right " for="form-field-1">&nbsp; </label>
                <br>
                <button type="button" name="btn-minus" class="btn btn-sm btn-danger btn-minus">
                    <span class="glyphicon glyphicon-minus"></span>
                </button>
            </div>
        </div>
        <div class="row" id="xsecs-widget-show-demo" style="margin-top: 15px"></div>
    </div>
    <div id="show-demo" class="progress-bar hide" style="background-color: #002F31;width:49%;padding-bottom: 5px;padding-top: 5px">
        <span style="font: 180% Arial; font-size: 20px;color: #ffffee;margin-top: 3px !important" data-text="item">指标</span><br>
        <span style="font: 180% Arial; font-size: 20px;color: #ffffee;margin-bottom: 3px !important">0</span>
    </div>

    <div id="simple-colorpicker" style="margin-left: 10px;margin-top: 2px" class="col-sm-3 hide">
        <select class="simple-colorpicker hide">
            {% for defalurColor in defalurColors %}
                <option value="{{ defalurColor }}">{{ defalurColor }}</option>
            {% endfor %}
        </select>
    </div>
</div>

<!-- 配置中继号码 -->
<div id="dialog-phone-monitor" class="hide" style="height: auto">
    <div class="widget-main hide" id="monitor-phone-widget" style="margin-bottom: 120px">
        <div class="row hide">
            <div class="col-xs-12">
                <form class="form-horizontal" role="form">
                    <div class="form-group">
                        <label class="col-sm-3 control-label no-padding-right" for="form-field-1"> {{ 'Belong phones'|trans }} </label>
                        <div class="col-sm-9">
                            <select id="phone" name="phone" class="chosen-select-2" multiple="multiple" style="width: 300px;">
                                {% for phone in phones %}
                                    <option value="{{ phone }}">{{ phone }}</option>
                                {% endfor %}
                            </select>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="widget-toolbox padding-8 clearfix">
    {{ button('Save Config', 'save-monitor-config', 'fa-save', 'btn-info') }}
</div>

<FORM id="screen_info_form" action="{{ path('icsoc_monitor_screen_bigscreen_preview') }}" method="post" target="preview">
    <input type="text" name="screen_info" id="screen_info" class="hide">
    <input type="text" name="role_id" id="role_id" class="hide">
</Form>
<script type="text/javascript" src="{{ asset('bundles/icsocui/plugin/select2/select2.min.js') }}"></script>
<script type="text/javascript">
    $("#phone").select2({
            formatNoMatches:function(){return""}
        }
    );
    /** 监控配置相关参数 validSecs需要设置有效通话量的指标，xsecs X秒接通量、放弃量*/
    var monitorParams = {{ paramsSettingItems|raw }};

    /** AceSpinner */
    var monitorAceSpinner = {value:26,min:14,max:28,step:1, on_sides: true, icon_up:'ace-icon fa fa-plus smaller-75', icon_down:'ace-icon fa fa-minus smaller-75', btn_up_class:'btn-success' , btn_down_class:'btn-danger'};

    /** AceAgentSpinner */
    var monitorAceAgentSpinner = {value:14,min:14,max:16,step:1, on_sides: true, icon_up:'ace-icon fa fa-plus smaller-75', icon_down:'ace-icon fa fa-minus smaller-75', btn_up_class:'btn-success' , btn_down_class:'btn-danger'};

    /** mainFields样式配置 */
    var monitorConfig = {{ mainFields|raw }};

    /** mainField样式配置 */
    var mainField = {{ mainField|raw }};

    /** 坐席状态相关配置 */
    var agents = {{ agents|raw }};

    /** 坐席状态默认配置,动态添加大屏监控会用到 */
    var agent = {{ agent|raw }};

    /** 当前配置指标文本 */
    var currentMonitorItemText = '';

    /** 当前配置的指标标识 */
    var currentMonitorItem = '';

    /** 当前配置颜色的元素（背景颜色、字体颜色）*/
    var currentColorElement = '';

    $(document).ready(function(){
        /** 动态添加大屏监控 */
        $("#monitor_config_box .widget-toolbar [data-action='settings'] .fa-plus").on('click', function () {
            if (click_id=="") {
                $.gritter.add({
                    title: '{{ 'Prompt'|trans }}',
                    text: '{{ 'You did not select any role cannot perform this operation'|trans }}!',
                    class_name: 'gritter-error'
                });

                return false;
            }

            /**
             * .widget-body-inner属性问题
             * 若存在，则获取widget-body-inner下的widet-main属性
             * 若不存在，则获取widget-main下的属性
             */
            if ($("#monitor .widget-body-inner").length > 0) {
                var $append = $("#monitor").children().children().eq(1);
            } else {
                var $append = $("#monitor").children().eq(1);
            }
            if ($append.children().length > 5 ) {
                $.gritter.add({
                    title: '{{ 'Prompt'|trans }}',
                    text: '{{ 'Can Not continue to add'|trans }}',
                    class_name: 'gritter-success'
                });
                return false;
            }
            var $clone = $append.children().first().clone();
            $append.append($clone);

            /** 随机生成大屏监控ID */
            var id = getRandomString("monitorConfigItemBox");
            $append.children().last().attr('id', id);
            $append.children().last().attr('config-id', 0);
            monitorConfig[id] = mainField;
            agents[id] = agent;
        });

        $("#dialog-message-monitor").on('blur', 'input[name="threshold"]', function () {
            var value = $(this).val();
            var regex = /^0?[0-9]*$/;
            if (!regex.test(value)) {
                $(this).val(0);
            }
        });

        $("#dialog-message-monitor").on('input propertychange', 'input[name="fontColor"],input[name="background"]', function() {
            if ($.inArray(currentMonitorItem, monitorParams.xsecs) != -1) {
                var index = $(this).closest('.row').index();
                if (currentColorElement == 'background') {
                    $('#xsecs-widget-show-demo').children().eq(index-1).css('background-color',$(this).val());
                    $(this).prevAll('input[name=background-hide]').val(rgb2hex($(this).val()));
                } else {
                    $('#xsecs-widget-show-demo').children().eq(index-1).find('span').css('color',$(this).val());
                }
            }

            if (currentColorElement == 'background') {
                $("#monitor-itmes-widget .progress-bar").css('background-color',$(this).val());
                $(this).prevAll('input[name=background-hide]').val(rgb2hex($(this).val()));
            } else {
                $("#monitor-itmes-widget .progress-bar").find('span').css('color',$(this).val());
            }
        });

        /** 删除大屏监控 */
        $('#monitor').on('click', '.fa-minus', function () {
            if ($("#monitor .widget-body-inner").length > 0) {
                var $append = $("#monitor").children().children().eq(1);
            } else {
                var $append = $("#monitor").children().eq(1);
            }
            if ($append.children().length <= 1 ) {
                $.gritter.add({
                    title: '{{ 'Prompt'|trans }}',
                    text: '{{ 'Can Not continue to Delete'|trans }}',
                    class_name: 'gritter-error'
                });
                return false;
            } else {
                $(this).closest('.widget-box').remove();
            }
        });

        /** 颜色选择点击事件。处理选择器位置 */
        $("#dialog-message-monitor").on('click', 'input[name="fontColor"],input[name="background"]', function() {
            currentColorElement = $(this).attr('name');
            var $colorpickerClone = $(".colorpicker");
            $(this).parent().append($colorpickerClone);
            var t = $(this).position().top+35+'px';
            var l = $(this).position().left+'px';
            $('.colorpicker').css({"top":t ,"left":l});
        });


        /** 是否显示配置信息 */
        $("#monitor").on('click', '.widget-header input[type="checkbox"][datatype="is-show"]', function() {
            if ($(this).prop("checked")) {
                var data_text = $(this).attr('data-text');
                if (data_text == 'group') {
                    if ($(this).parent().parent().parent().parent().children().find("input[type='checkbox'][datatype='is-bygroup-show']").prop("checked")) {
                        $(this).parent().parent().parent().parent().children().find("input[type='checkbox'][datatype='is-bygroup-show']").trigger('click');
                    }
                }
                $(this).parent().parent().next().removeClass('hide');
                /*if (dataText == 'queue') {
                 $(this).closest(".widget-main").find('.widget-header input[type="checkbox"][data-text=group]').prop( "checked", false );
                 }
                 if (dataText == 'group') {
                 $(this).closest(".widget-main").find('.widget-header input[type="checkbox"][data-text=queue]').prop( "checked", false );
                 }*/
            } else {
                $(this).parent().parent().next().addClass('hide');
            }
        });

        /** 是否按业务组显示 */
        $("#monitor").on('click', 'input[type="checkbox"][datatype="is-bygroup-show"]', function () {
            if ($(this).prop("checked")) {
                //勾选上这个
                if (!$(this).parent().parent().children().find("input[type='checkbox'][name='agent-show']").prop("checked")) {
                    $(this).parent().parent().children().find("input[type='checkbox'][name='agent-show']").trigger('click');
                }
                //判断数据上一层的checked
                if ($(this).parent().parent().parent().parent().children().find("input[type='checkbox'][datatype='is-show'][data-text='group']").prop("checked")) {
                    $(this).parent().parent().parent().parent().children().find("input[type='checkbox'][datatype='is-show'][data-text='group']").trigger('click');
                }
                //技能组是否显示
                if (!$(this).parent().parent().parent().parent().children().find("input[type='checkbox'][datatype='is-show'][data-text='queue']").prop("checked")) {
                    $(this).parent().parent().parent().parent().children().find("input[type='checkbox'][datatype='is-show'][data-text='queue']").trigger('click');
                }
            }
        });

        /** 预览效果 */
        $('#monitor').on('click', '.fa-eye', function () {
            var $element = $(this).closest('.widget-box');
            var monitroWidgetBox = $element.attr("id");
            var configId = $element.attr("config-id");
            var monitor_info = {};
            var fields = {"system":{},"queue":{},"group":{}};
            var agentConfig = {"is_show":0,"type":1};
            var agentShowType = 1;
            $element.find('input[type="checkbox"][datatype="is-show"]:checked').each(function() {
                if ($(this).attr('data-text') != 'agent') {
                    $(this).parent().parent().next().find('input[type="checkbox"]:checked').each(function() {
                        var dataType = $(this).attr('data-type');//报表的类型
                        var id = $(this).val();//指标ID
                        var name = $(this).attr('data-text');//指标name
                        if (dataType == 'group') {
                            agentShowType = 2;
                        }
                        monitorConfig[monitroWidgetBox][dataType][id]['id'] = id;
                        monitorConfig[monitroWidgetBox][dataType][id]['name'] = name;
                        fields[dataType][id] = monitorConfig[monitroWidgetBox][dataType][id];

                    });
                } else {
                    agentConfig = agents[monitroWidgetBox];
                    if ($(this).parent().parent().children().find("input[type='checkbox'][name='agent-group-show']").prop("checked")) {
                        agentConfig['is_group_show'] = 1;
                    } else {
                        agentConfig['is_group_show'] = 0;
                    }
                    if (typeof agents[monitroWidgetBox]['busy']['busy_data'] != 'undefined' ) {
                        var busyData = [];
                        $.each(agents[monitroWidgetBox]['busy']['busy_data'], function (index, data) {
                            busyData.push(data)
                        });

                        agents[monitroWidgetBox]['busy']['busy_data'] = busyData;
                    }
                    agentConfig['is_show'] = 1;
                    agentConfig['type'] = agentShowType;
                }
            });

            var mainFields = [];
            $.each(fields, function (index, data) {
                var fieldsType = {"type":"","fields":[]};
                $.each(data, function (ind, field) {
                    fieldsType["fields"].push(field);
                });

                var fields = [];
                switch (index) {
                    case 'system':
                        fieldsType["type"] = 1;
                        mainFields.push(fieldsType);
                        break;
                    case 'queue':
                        fieldsType["type"] = 2;
                        if (fieldsType["fields"].length > 0) {
                            mainFields.push(fieldsType);
                        }
                        break;
                    case 'group':
                        fieldsType["type"] = 3;
                        if (fieldsType["fields"].length > 0) {
                            mainFields.push(fieldsType);
                        }
                        break;
                }
            });

            monitor_info["id"] = configId;
            monitor_info['name'] = $.trim($(this).find('.widget-title input[name="monitor_name"]').val());
            monitor_info['refresh'] = $.trim($(this).find('.widget-title input[name="refresh"]').val());
            monitor_info["mainFields"] = mainFields;
            monitor_info['agent'] = agentConfig;
            $("#screen_info").val(JSON.stringify(monitor_info));
            $("#role_id").val(click_id);
            window.open('','preview','');
            $("#screen_info_form").submit();
        });

        /** 保存配置 */
        $('#save-monitor-config').on('click', function () {
            if (click_id=="") {
                $.gritter.add({
                    title: '{{ 'Prompt'|trans }}',
                    text: '{{ 'You did not select any role cannot perform this operation'|trans }}!',
                    class_name: 'gritter-error'
                });

                return false;
            }
            $(this).attr('disabled', true);
            var monitor_screen = [];
            var monitorNames = [];
            var existName = '';
            $(this).parent().parent().children().eq(1).children().each(function() {
                var monitroWidgetBox = $(this).attr("id");
                var configId = $(this).attr("config-id");
                var monitor_info = {};
                var fields = {"system":{},"queue":{},"group":{}};
                var agentConfig = {"is_show":0,"type":1};

                var monitorName =  $.trim($(this).find('.widget-title input[name="monitor_name"]').val());
                if ($.inArray(monitorName, monitorNames) != -1) {
                    existName = monitorName;
                    return false;
                }
                monitorNames.push(monitorName);
                var agentShowType = 1;
                $(this).find('input[type="checkbox"][datatype="is-show"]:checked').each(function() {
                    if ($(this).attr('data-text') != 'agent') {
                        $(this).parent().parent().next().find('input[type="checkbox"]:checked').each(function() {
                            var dataType = $(this).attr('data-type');//报表的类型
                            if (dataType == 'group') {
                                agentShowType = 2;
                            }
                            var id = $(this).val();//指标ID
                            var name = $(this).attr('data-text');//指标name

                            monitorConfig[monitroWidgetBox][dataType][id]['id'] = id;
                            monitorConfig[monitroWidgetBox][dataType][id]['name'] = name;
                            fields[dataType][id] = monitorConfig[monitroWidgetBox][dataType][id];

                        });
                    } else {
                        agentConfig = agents[monitroWidgetBox];
                        if ($(this).parent().parent().children().find("input[type='checkbox'][name='agent-group-show']").prop("checked")) {
                            agentConfig['is_group_show'] = 1;
                        } else {
                            agentConfig['is_group_show'] = 0;
                        }
                        if (typeof agents[monitroWidgetBox]['busy']['busy_data'] != 'undefined' ) {
                            var busyData = [];
                            $.each(agents[monitroWidgetBox]['busy']['busy_data'], function (index, data) {
                                busyData.push(data)
                            });

                            agents[monitroWidgetBox]['busy']['busy_data'] = busyData;
                        }
                        agentConfig['is_show'] = 1;
                        agentConfig['type'] = agentShowType;
                    }

                });

                var mainFields = [];
                $.each(fields, function (index, data) {
                    var fieldsType = {"type":"","fields":[]};
                    $.each(data, function (ind, field) {
                        fieldsType["fields"].push(field);
                    });

                    var fields = [];
                    switch (index) {
                        case 'system':
                            fieldsType["type"] = 1;
                            mainFields.push(fieldsType);
                            break;
                        case 'queue':
                            fieldsType["type"] = 2;
                            if (fieldsType["fields"].length > 0) {
                                mainFields.push(fieldsType);
                            }
                            break;
                        case 'group':
                            fieldsType["type"] = 3;
                            if (fieldsType["fields"].length > 0) {
                                mainFields.push(fieldsType);
                            }
                            break;
                    }
                });
                monitor_info["id"] = configId;
                monitor_info['name'] = $.trim($(this).find('.widget-title input[name="monitor_name"]').val());
                monitor_info['refresh'] = $.trim($(this).find('.widget-title input[name="refresh"]').val());
                monitor_info["mainFields"] = mainFields;
                monitor_info['agent'] = agentConfig;
                monitor_screen.push(monitor_info);
            });

            if (existName != '') {
                $.gritter.add({
                    title: '{{ 'Prompt'|trans }}',
                    text: '【'+existName+'】已存在,请修改大屏监控名称!',
                    class_name: 'gritter-error'
                });

                $(this).attr('disabled', false);
                return false;
            }

            $.ajax({
                url: '{{ path("icsoc_security_role_monitor_config") }}',
                dataType: 'json',
                type: 'post',
                data: {monitor_info: JSON.stringify(monitor_screen), roleId:click_id},
                success: function (response) {
                    $("#save-monitor-config").attr('disabled', false);
                    if (response.code != 200) {
                        $.gritter.add({
                            title: '{{ 'Prompt'|trans }}',
                            text: response.message,
                            class_name: 'gritter-error'
                        });
                    } else {
//                        var i = 0;
//                        $("#monitor").children().children().eq(1).children().each(function() {
//                            $(this).attr("config-id",response.data[i]);
//                            i++;
//                        });
                        $("#monitor_config_box [data-action=reload] .fa-refresh").trigger('click');
                        $.gritter.add({
                            title: '{{ 'Prompt'|trans }}',
                            text: '{{ 'Add success'|trans }}',
                            class_name: 'gritter-success'
                        });
                    }
                }
            });
        });

        $('#monitor').on('click', '.fa-edit', function () {
            var topL0 = $("#dialog-message-report").offset().top;
            $(document).scrollTop(topL0+'px');
            var data_type = $(this).attr('data-type');
            var data_text = $(this).attr('data-text');
            var data_id = $(this).attr('data-id');
            var datatype = $(this).attr('datatype');
            var monitroWidgetBox = $(this).closest(".widget-box").attr('id');
            currentMonitorItemText = data_text;
            currentMonitorItem = data_id;
            var buttons = [
                {
                    text: "{{ 'Cancel'|trans}}",
                    "class" : "btn btn-xs",
                    click: function() {
                        $( this ).dialog( "close" );
                    }
                },
                {
                    text: "{{ 'OK'|trans}}",
                    "class" : "btn btn-primary btn-xs",
                    click: function() {
                        /*if (datatype != 'agent' && $.inArray(data_id, monitorParams.validSecs) != '-1' && $.trim($("#valid_call_secs").val()) == '') {
                         alert("请输入有效通话时长");
                         }*/

                        /** X秒接通量、放弃量处理,参数处理 */
                        if ($.inArray(data_id, monitorParams.xsecs) != -1) {
                            var style = {"id":data_id,"name":data_text,"fieldType":1,"paramName":[]};
                            $('#xsecs-widget').children().not('.hide').each(function() {
                                var chlidStyle = {"id":"","name":"","paramValue":"","style":{}};
                                var paramValue = $.trim($(this).find('input[name="xsecs"]').val());
                                if (isNaN(paramValue) || paramValue == '') {
                                    return false;
                                }
                                chlidStyle['id'] = data_id+paramValue;
                                chlidStyle['name'] = data_text.replace('%X%', paramValue);
                                chlidStyle['paramValue'] = paramValue;
                                chlidStyle['style']['background'] = $.trim($(this).find('input[name="background-hide"]').val());
                                chlidStyle['style']['fontColor'] = $.trim($(this).find('input[name="fontColor"]').val());
                                chlidStyle['style']['fontSize'] = $.trim($(this).find('input[name="fontSize"]').val())+'px';

                                style['paramName'].push(chlidStyle);

                            });
                        } else {
                            var style = {"id":"","name":"","fieldType":0,"style":{},"params":{},"phones":""};
                            var $element = $("#monitor-itmes-widget").not(".hide").children().eq(1);
                            style['style']['background'] = $.trim($element.find('input[name="background-hide"]').val());
                            style['style']['fontColor'] = $.trim($element.find('input[name="fontColor"]').val());
                            style['style']['fontSize'] = $.trim($element.find('input[name="fontSize"]').val())+'px';
                            /** 有效通话量,参数处理 */
                            if ($.inArray(data_id, monitorParams.validSecs) != -1) {
                                style['fieldType'] = 1;
                                style['params']['paramName'] = 'validSecs';
                                style['params']['paramValue'] = $.trim($('#valid_call_secs').val());
                            }
                        }

                        /** 坐席状态样式 */
                        if (datatype == 'agent') {
                            var $element = $("#monitor-itmes-widget").children().eq(1);
                            var threshold = $element.find('input[name="threshold"]').val();
                            if (threshold == "") {
                                threshold = 0;
                            }

                            if (data_type != 'busy') {
                                agents[monitroWidgetBox][data_type] = style['style'];
                                agents[monitroWidgetBox][data_type]['threshold'] = threshold;
                            } else {
                                if ("{{ ifFasreason != true }}") {
                                    agents[monitroWidgetBox][data_type]['if_hasreason'] = 0;
                                } else {
                                    agents[monitroWidgetBox][data_type]['if_hasreason'] = 1;
                                }
                                agents[monitroWidgetBox][data_type]['busy_data'][data_id]['id'] = data_id;
                                agents[monitroWidgetBox][data_type]['busy_data'][data_id]['name'] = data_text;
                                agents[monitroWidgetBox][data_type]['busy_data'][data_id]['style'] = style['style'];
                                agents[monitroWidgetBox][data_type]['busy_data'][data_id]['threshold'] = threshold;
                            }
                        } else {
                            var oldstyle = monitorConfig[monitroWidgetBox][data_type][data_id];
                            if (oldstyle['phones'] != "") {
                                style['phones'] = oldstyle['phones'];
                            }
                            monitorConfig[monitroWidgetBox][data_type][data_id] = style;
                        }
                        $( this ).dialog( "close" );
                    }
                }
            ];

            /** X秒接通量、放弃量处理,参数处理 */
            if ($.inArray(data_id, monitorParams.xsecs) != -1) {
                $("#monitor-itmes-widget").addClass('hide');
                $("#xsecs-widget").removeClass('hide');

                buttons.push({
                    text: "{{ 'Add XSecs Items'|trans }}",
                    "class" : "btn btn-plus btn-popover-monitor",
                    "attr" :{"data-rel":"popover","data-placement":"top","data-content":"Popover without a title!"},
                    click: function() {
                        if ($("#xsecs-widget").children().length == 6) {
                            $('.btn-popover-monitor').popover({html:true});
                            $('.btn-popover-monitor').attr("data-content","{{ 'Can Not continue to add'|trans }}");
                        }

                        if ($("#xsecs-widget").children().length > 6) {
                            return false;
                        }

                        var params = {"paramValue":"","fontColor":'{{ defautFontColor }}',"fontSize":"{{ defautFontSize }}px","background":"{{ defautBackground }}"};
                        xsecsItemSetting(params);
                    }
                })

            } else {
                $("#monitor-itmes-widget").removeClass('hide');
                $("#xsecs-widget").addClass('hide');
            }

            /** 删除动态加添的元素 */
            $(".dynamic").remove();
            $(".dropdown-colorpicker").remove();

            if (datatype != 'agent') {
                setFormAttr(datatype, data_id, monitorConfig[monitroWidgetBox][data_type][data_id],data_text);

            } else {
                var param = {};
                if ("{{ ifFasreason != true }}" || data_type != 'busy') {
                    var style = {};
                    style['background'] = agents[monitroWidgetBox][data_type]['background'];
                    style['fontColor'] = typeof agents[monitroWidgetBox][data_type]['fontColor'] == "undefined" ? "{{ defautFontColor }}" : agents[monitroWidgetBox][data_type]['fontColor'];
                    style['fontSize'] = typeof agents[monitroWidgetBox][data_type]['fontSize'] == "undefined" ? "{{ defautFontSize }}px" : agents[monitroWidgetBox][data_type]['fontSize'];
                    param['style'] = style;
                    param['threshold'] = typeof agents[monitroWidgetBox][data_type]['threshold'] == "undefined" ? 0 : agents[monitroWidgetBox][data_type]['threshold'];
                } else {
                    if (typeof agents[monitroWidgetBox][data_type]['busy_data'].length == "number") {
                        var array = agents[monitroWidgetBox][data_type]['busy_data'];
                        for (var i=0; i<=array.length-1; i++) {
                            if (array[i]['id'] == data_id) {
                                param = agents[monitroWidgetBox][data_type]['busy_data'][i];
                                break;
                            }
                        }
                    } else {
                        param = agents[monitroWidgetBox][data_type]['busy_data'][data_id];
                    }
                }
                setFormAttr(datatype, data_id, param, data_text);
            }

            var dialog = $( "#dialog-message-monitor" ).removeClass('hide').dialog({
                modal: true,
                title: "{{ 'Itmes Config'|trans }}",
                title_html: true,
                width:700,
                buttons:buttons,
            });

            var topL0 = $("#dialog-message-monitor").offset().top;
            $(document).scrollTop('1000px');
        });

        //配置中继号码
        $("#monitor").on('click', '.fa-cogs', function () {
            var topL0 = $("#dialog-message-report").offset().top;
            $(document).scrollTop(topL0+'px');
            var data_type = $(this).attr('data-type');
            var data_text = $(this).attr('data-text');
            var data_id = $(this).attr('data-id');
            var datatype = $(this).attr('datatype');
            var monitroWidgetBox = $(this).closest(".widget-box").attr('id');
            currentMonitorItemText = data_text;
            currentMonitorItem = data_id;
            //配置下中继号码
            var buttons = [
                {
                    text: "{{ 'Cancel'|trans}}",
                    "class" : "btn btn-xs",
                    click: function() {
                        $( this ).dialog( "close" );
                    }
                },
                {
                    text: "{{ 'OK'|trans }}",
                    "class": "btn btn-primary btn-xs",
                    click: function () {
                        var phones = $(this).find('select[name="phone"]').val();
                        var style = monitorConfig[monitroWidgetBox][data_type][data_id];
                        if (style != '') {
                            style['phones'] = phones;
                        } else {
                            style = {"id":"","name":"","fieldType":0,"style":{},"params":{},"phones":""};
                        }
                        monitorConfig[monitroWidgetBox][data_type][data_id] = style;
                        $( this ).dialog( "close" );
                    }
                }
            ];
            setFormAttr(datatype, data_id, monitorConfig[monitroWidgetBox][data_type][data_id], data_text);
            $("#monitor-phone-widget").removeClass('hide');
            $("#monitor-phone-widget .row").removeClass('hide');
            var dialog = $( "#dialog-phone-monitor" ).removeClass('hide').dialog({
                modal: true,
                title: "{{ 'Phone Config'|trans }}",
                title_html: true,
                width:700,
                buttons:buttons,
            });
            var topL0 = $("#dialog-phone-monitor").offset().top;
            $(document).scrollTop('1000px');
        });

        /** 动态添加X秒指标数量超限提示信息隐藏 */
        $("body").on("mouseout", ".btn-popover-monitor", function () {
            if ($(this).next().hasClass('popover') && $(this).next().css("display") == 'block') {
                $(this).next().css("display","none");
            }
        });

        /** 指标文字大小设置 */
        $("#dialog-message-monitor").on('click', '.ace-spinner .fa-plus,.btn-xs', function() {
            var fontSize = $(this).closest('.ace-spinner').find('input[name="fontSize"]').val();
            if ($.inArray(currentMonitorItem, monitorParams.xsecs) == '-1') {
                $("#monitor-itmes-widget .progress-bar").find('span').css('font-size',fontSize+'px');
            } else {
                var index = $(this).closest('.row').index();
                $('#xsecs-widget-show-demo').children().eq(index-1).find('span[data-text="item"]').css('font-size',fontSize+'px');
            }
        });

        /** 删除X秒接通。放弃量指标样式设置 */
        $("#xsecs-widget").on('click', '.btn-minus', function () {
            var $element = $(this).closest('.row');
            var index = $element.index();
            $element.remove();
            $('#xsecs-widget-show-demo').children().eq(index-1).remove();

            if ($("#xsecs-widget").children().length < 5) {
                $('.btn-popover-monitor').popover({html:false});
            }
        });

        /** X秒时长失去交焦点事件,改变demo显示文字 */
        $("#xsecs-widget").on('blur', 'input[name="xsecs"]', function () {
            var index = $(this).closest('.row').index();
            var value = $(this).val();
            $('#xsecs-widget-show-demo').children().eq(index-1).find('span[data-text="item"]').html(currentMonitorItemText.replace('%X%', value));
        });

        $('#dialog-message-monitor').on('change', '.simple-colorpicker', function() {
            $(this).parent().siblings('input[name=background-hide]').val(this.value);
            if ($.inArray(currentMonitorItem, monitorParams.xsecs) == '-1') {
                $("#monitor-itmes-widget .progress-bar").css('background-color',this.value);
                $(this).closest('.col-sm-9').find('.colorpicker-input').val(this.value);
                $(this).closest('.col-sm-9').find('.colorpicker-input').colorpicker('setValue', this.value);
            } else {
                var index = $(this).closest('.row').index();
                $(this).closest('.control-group').find('.colorpicker-input').val(this.value);
                $(this).closest('.control-group').find('.colorpicker-input').colorpicker('setValue', this.value);
                $('#xsecs-widget-show-demo').children().eq(index-1).css('background-color',this.value);
            }
        });
    });

    /**
     * 设置表单属性
     *
     * @param field
     */
    function setFormAttr(type, field, param, data_text)
    {
        $("#valid_call_secs").val('');
        $("#xsecs").val('');
        if ($.inArray(field, monitorParams.validSecs) == '-1') {
            $("#valid_call_secs").attr('disabled', true);
            $("#valid-secs-grou").addClass('hide');
        } else {
            $("#valid_call_secs").attr('disabled', false);
            $("#valid-secs-grou").removeClass('hide');
            if (typeof param.params != 'undefined' ) {
                $("#valid_call_secs").val(param.params.paramValue);
            }
        }
        if (type == 'agent') {
            $("#time-threshold").removeClass('hide');
        } else {
            $("#time-threshold").addClass('hide');
        }
        //回显中继号码
        if (field == 'ivrInboundTotalNum') {
            if (typeof param.phones != 'undefined') {
                $("#phone").val(function(){
                    return param.phones;
                }).trigger("change");
            }
        }

        if ($.inArray(field, monitorParams.xsecs) != '-1') {
            if (typeof param.paramName == 'undefined' || param.paramName.length == 0) {
                var params = {"paramValue":"10","fontColor":'{{ defautFontColor }}',"fontSize":"{{ defautFontSize }}px","background":"{{ defautBackground }}"};
                xsecsItemSetting(params);

            } else {
                $.each(param.paramName, function (index, data) {
                    var params = {"paramValue":data.paramValue,"fontColor":data.style.fontColor,"fontSize":data.style.fontSize,"background":data.style.background};
                    xsecsItemSetting(params);
                });
            }
        } else {
            var background = param.style.background;
            var fontColor = typeof param.style.fontColor == "undefined" ? "{{ defautFontColor }}" : param.style.fontColor;
            var fontSize = typeof param.style.fontSize == "undefined" ? "{{ defautFontSize }}px" : param.style.fontSize;
            var threshold = typeof param.threshold == "undefined" ? 0 : param.threshold;
            fontSize = fontSize.toString();
            /** 监控指标demo 显示 */
            var $clone = $("#show-demo").clone();
            $clone.addClass('dynamic');
            $clone.removeClass('hide');
            $clone.removeAttr("id");
            $clone.find('span[data-text="item"]').html(data_text);
            $clone.css('background-color',background);
            $clone.find('span').css('color',fontColor);
            $clone.find('span').css('font-size',fontSize);
            $(".monitor-itmes-show-demo").append($clone);

            var $clone = $("#monitor-itmes-widget").children().first().clone();
            $clone.addClass('dynamic');
            $clone.removeClass('hide');
            $clone.find("input[name='background']").val(background);
            $clone.find("input[name='background-hide']").val(background);
            $clone.find("input[name='threshold']").val(threshold);

            var $simpleColorpicker = $("#simple-colorpicker").clone();
            $simpleColorpicker.removeAttr("id");
            $simpleColorpicker.removeClass("hide");
            $simpleColorpicker.find('.simple-colorpicker').val(background);
            $simpleColorpicker.find('.simple-colorpicker').ace_colorpicker();
            $clone.find("input[name='background']").after($simpleColorpicker);
            $clone.find("input[name='fontSize']").val(fontSize.replace('px', ''));
            $clone.find("input[name='fontColor']").val(fontColor);
            if (type == 'agent') {
                $clone.find('.fontSize').ace_spinner(monitorAceAgentSpinner);
            } else {
                $clone.find('.fontSize').ace_spinner(monitorAceSpinner);
            }

            $("#monitor-itmes-widget").append($clone);
            $('.colorpicker-input').colorpicker();
            $(".colorpicker").mouseup(function(){
                var styleColor = $(this).find(".colorpicker-color").children().first().attr('style');
                $(this).siblings("span").css('background-color',styleColor);

                if (currentColorElement == 'background') {
                    $("#monitor-itmes-widget .progress-bar").css('background-color',styleColor);
                    $(this).prevAll('input[name=background-hide]').val(rgb2hex(styleColor));
                } else {
                    $("#monitor-itmes-widget .progress-bar").find('span').css('color',styleColor);
                }
            });

            $('.simple-colorpicker').ace_colorpicker();
        }
    }

    /**
     * X秒指标设置
     */
    function xsecsItemSetting(params)
    {
        params.fontSize = typeof params.fontSize == "undefined" ? "{{ defautFontSize }}px" : params.fontSize;
        params.fontSize = params.fontSize.toString();
        /** 监控指标demo 显示 */
        var $clone = $("#show-demo").clone();
        $clone.removeClass('hide');
        $clone.addClass('dynamic');
        $clone.removeAttr("id");
        if (typeof params.paramValue == 'undefined' || params.paramValue == '') {
            var value = 'X';
        } else {
            var value = params.paramValue;
        }

        $clone.find('span[data-text="item"]').html(currentMonitorItemText.replace('%X%', value));
        $clone.css('background-color',params.background);

        $clone.find('span').css('color',params.fontColor);
        $clone.find('span').css('font-size',params.fontSize);
        $('#xsecs-widget-show-demo').append($clone);
        var $clone = $("#xsecs-widget").children().first().clone();
        $clone.removeClass('hide');
        $clone.addClass('dynamic');
        $clone.find("input[name='xsecs']").val(params.paramValue);
        $clone.find("input[name='fontColor']").val(params.fontColor);
        $clone.find("input[name='background']").val(params.background);
        $clone.find("input[name='background-hide']").val(params.background);
        $clone.find("input[name='fontSize']").val(params.fontSize.replace('px', ''));
        var $simpleColorpicker = $("#simple-colorpicker").clone();
        $simpleColorpicker.removeAttr("id");
        $simpleColorpicker.removeClass("hide");
        $simpleColorpicker.find('.simple-colorpicker').val(params.background);
        $simpleColorpicker.find('.simple-colorpicker').ace_colorpicker();
        $clone.find("input[name='background']").after($simpleColorpicker);

        $clone.find('.fontSize').ace_spinner(monitorAceSpinner);
        $("#xsecs-widget-show-demo").before($clone);

        $('.colorpicker-input').colorpicker();

        $(".colorpicker").mouseup(function(){
            var index = $(this).closest('.row').index();
            var styleColor = $(this).find(".colorpicker-color").children().first().attr('style');
            if (currentColorElement == 'background') {
                $('#xsecs-widget-show-demo').children().eq(index-1).css('background-color',styleColor);
                $(this).prevAll('input[name=background-hide]').val(rgb2hex(styleColor));
            } else {
                $('#xsecs-widget-show-demo').children().eq(index-1).find('span').css('color',styleColor);
            }
        });
    }

    function zero_fill_hex(num, digits) {
        var s = num.toString(16);
        while (s.length < digits)
            s = "0" + s;
        return s;
    }

    /**
     * 验证刷新时间
     * @param key
     */
    function check_refresh(key)
    {
        var value = $.trim($(key).val());
        var reg = /^[1-9]\d{0,2}$/;

        if (reg.test(value) === false || value < 5) {
            $(key).focus().val(10);
            alert("刷新时间必须为5-999的整数");
        }
    }

    function rgb2hex(rgb) {

        if (rgb.charAt(0) == '#')
            return rgb;

        var ds = rgb.split(/\D+/);
        var decimal = Number(ds[1]) * 65536 + Number(ds[2]) * 256 + Number(ds[3]);
        return "#" + zero_fill_hex(decimal, 6);
    }
</script>